<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="rules"
      autocomplete="off"
      class="login-form"
      label-position="left"
    >
      <div class="title-container">
        <div class="title">
          <div>登录</div>
          <div class="titles">
            /login up
          </div>
        </div>
      </div>
      <span>
        <el-form-item prop="account">
          <el-input
            size="mini"
            ref="account"
            v-model="loginForm.account"
            :placeholder="$t('login.username')"
            autocomplete="off"
            name="account"
            prefix-icon="el-icon-user"
            type="text"
            @keyup.enter.native="handleLogin"
          />
        </el-form-item>
        <el-form-item prop="password">
          <!-- :show-password="true" -->
          <el-input
            size="mini"
            ref="password"
            v-model="loginForm.password"
            :placeholder="$t('login.password')"
            autocomplete="off"
            name="password"
            prefix-icon="el-icon-lock"
            auto-complete="on"
            :type="passwordType"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
        <div style="display:flex;align-items: center;">
          <el-form-item v-show="isCaptcha" class="code-input" prop="code">
            <el-input
              size="mini"
              ref="code"
              v-model="loginForm.code"
              :placeholder="$t('login.code')"
              autocomplete="off"
              name="code"
              prefix-icon="el-icon-lock"
              style="width: 70%"
              type="text"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <img
            v-show="isCaptcha"
            :src="imageCode"
            alt="codeImage"
            class="code-image"
            @click="getCodeImage"
          />
        </div>
        <div class="login-but-box">
          <el-button
            :loading="loading"
            class="login-but"
            type="primary"
            @click.native.prevent="handleLogin"
            >{{ $t("login.logIn") }}</el-button
          >
        </div>
      </span>
    </el-form>
  </div>
</template>

<script>
import db from "@/utils/localstorage";
import { randomNum } from "@/utils";
import loginApi from "@/api/Login.js";
import { Base64 } from "js-base64";

export default {
  name: "Login",
  data() {
    return {
      //是否启用多租户
      isMultiTenant:
        process.env.VUE_APP_IS_MULTI_TENANT === "true" ? true : false,
      isCaptcha: process.env.VUE_APP_IS_CAPTCHA === "true" ? true : false,
      loginForm: {
        account: "",
        password: "",
        tenantView: "chenzhou", //显示用的
        tenant: "", //传递给后端的
        key: randomNum(24, 16),
        code: "",
        grantType:
          process.env.VUE_APP_IS_CAPTCHA === "true" ? "captcha" : "password"
      },
      passwordType: "password",
      rules: {
        account: {
          required: true,
          message: this.$t("rules.require"),
          trigger: "blur"
        },
        password: {
          required: true,
          message: this.$t("rules.require"),
          trigger: "blur"
        },
        code: {
          validator: (rule, value, callback) => {
            if (this.isCaptcha && value === "") {
              callback("验证码不能为空");
            } else {
              callback();
            }
            callback();
          },
          trigger: "blur"
        }
      },
      authUser: null,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      imageCode: "",
      page: {
        width: window.screen.width * 0.5,
        height: window.screen.height * 0.5
      }
    };
  },
  created() {},
  mounted() {
    db.clear();
    this.getCodeImage();
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
    },
    getCodeImage() {
      loginApi
        .getCaptcha(this.loginForm.key)
        .then(response => {
          const res = response.data;
          if (res.byteLength <= 100) {
            this.$message({
              message: this.$t("tips.systemError"),
              type: "error"
            });
          }
          return (
            "data:image/png;base64," +
            btoa(
              new Uint8Array(res).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
              )
            )
          );
        })
        .then(res => {
          this.imageCode = res;
        })
        .catch(e => {
          if (e.toString().indexOf("429") !== -1) {
            this.$message({
              message: this.$t("tips.tooManyRequest"),
              type: "error"
            });
          } else {
            this.$message({
              message: this.$t("tips.getCodeImageFailed"),
              type: "error"
            });
          }
        });
    },
    resolveLogo(logo) {
      return require(`@/assets/logo/${logo}`);
    },
    handleLogin() {
      this.loginForm.tenant = `${Base64.encode(this.loginForm.tenantView)}`;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loginSubmit();
        } else {
          return false;
        }
      });
    },
    loginSubmit() {
      this.loading = true;
      const that = this;
      this.$store.commit("account/setTenant", this.loginForm.tenant);
      loginApi
        .login(this.loginForm)
        .then(response => {
          // debugger;
          const res = response.data;
          if (res.isSuccess) {
            that.saveLoginData(
              res.data["token"],
              res.data["refreshToken"],
              res.data["expiration"]
            );
            that.saveUserInfo(res.data);
            that.getResource();
          } else {
            that.getCodeImage();
          }
        })
        .catch(() => {
          // if(error.response.data){
          //   this.$message({
          //     message: error.response.data.msg,
          //     type: "error"
          //   });
          // }
          that.getCodeImage();
        })
        .finally(() => (that.loading = false));
    },
    saveLoginData(token, refreshToken, expiration) {
      this.$store.commit("account/setToken", token);
      this.$store.commit("account/setRefreshToken", refreshToken);
      this.$store.commit("account/setExpireTime", expiration);
    },
    saveUserInfo(user) {
      this.$store.commit("account/setUser", {
        id: user.userId,
        account: user.account,
        name: user.name,
        avatar: user.avatar,
        workDescribe: user.workDescribe
      });
    },
    getResource() {
      loginApi.getResource().then(response => {
        const res = response.data;
        if (res.isSuccess) {
          const permissionsList = res.data;
          this.$store.commit(
            "account/setPermissions",
            permissionsList ? permissionsList : []
          );

          this.loginSuccess();
        } else {
          this.getCodeImage();
        }
      });
    },
    loginSuccess() {
      this.$message({
        message: this.$t("tips.loginSuccess"),
        type: "success"
      });
      this.$router.push("/");
    },
    loginSuccessCallback(user) {
      console.log(user);
    }
  }
};
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #555;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  .el-input {
    display: inline-block;
    width: 100%;
    border: 0px;

    input {
      background: transparent;
      border: 0px;
      color: #5189fb;
      padding-left: 40px;
      height: 40px;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-form-item__content {
    width: 100%;
    min-width: 150px;
    .el-input__icon {
      color: #5189fb;
      font-size: 24px;
    }
  }

  .el-form-item {
    background: #f9f9f9;
    border: 0px;
    border-radius: 2px;
    color: #454545;
    transition: all 0.3s;

    &:hover {
      border-color: #57a3f3;
    }
  }
}
</style>
<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #aaa;
$light_gray: #eee;

.login-container {
  background: url(../../assets/background.png) 50% no-repeat;
  background-size: cover;
  width: 100%;
  height: 100vh;

  .login-form {
    padding: 36px calc(100% - 93%);
    background: #fff;
    border-radius: 6px;

    .code-input {
      width: 50%;
      display: inline-block;
      vertical-align: middle;
    }

    .code-image {
      display: inline-block;
      vertical-align: top;
      margin-bottom: 22px;
      cursor: pointer;
    }

    .login-type {
      text-align: right;
      display: inline-block;
      width: 100%;
    }

    .logo-wrapper {
      display: inline-block;
      margin: 10px 0;

      img {
        width: 1.9rem;
        display: inline-block;
        margin: 0.8rem 0.8rem -0.8rem 0.8rem;
        cursor: pointer;

        &.radius {
          border-radius: 50%;
        }
      }
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .title-container {
    position: relative;

    .title {
      padding-left: 1rem;
      font-size: 2.25rem;
      color: #5189fb;
      margin: 0px auto 40px auto;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      .titles {
        font-size: 16px;
        margin-top: 37px;
        color: #d2d2d2;
      }
    }

    .set-language {
      color: #aaa;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0;
      cursor: pointer;
    }
  }
  .login-but-box {
    display: flex;
    align-items: center;
    justify-content: center;
    .login-but {
      width: 65%;
      // height: 50px;
      margin-top: 10%;
    }
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }

  @media screen and (max-width: 1100px) {
    .login-info {
      left: 8%;
    }
  }

  @media screen and (max-width: 970px) {
    .login-form {
      left: 50%;
    }
    .login-info {
      display: none;
    }
  }
}
.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
</style>
